package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.domain.User;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private QueryRunner queryRunner=new QueryRunner(DataSourceUtil.getDataSource());
    @Override
    public User selectByUserName(String username) {
        String sql=" select * from tb_user where username=? ";
        try {
            return queryRunner.query(sql ,new BeanHandler<>(User.class),username);
        } catch (SQLException e) {
            throw  new RuntimeException(e);
        }
    }

    @Override
    public void insert(User user) {
        String sql=" insert into tb_user values (null,?,?,?,?,?,?,?) ";
        Object[] params={user.getUsername(),user.getPassword(),user.getEmail(),user.getGender(),user.getFlag(),user.getRole(),user.getCode()};
        try {
            queryRunner.update(sql,params);
        } catch (Exception e) {
            throw  new RuntimeException(e);
        }
    }

    @Override
    public List<User> selectaName(String use, String gen) {
        String sql=" SELECT * FROM `tb_user` ";
        //Object[] param={use.};
        try {
            return queryRunner.query(sql,new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<User> selectAll(String where, List<Object> params, boolean flag) {
        String sql = "";
        if (!flag){
            sql = " SELECT * FROM tb_user "+where+" AND flag=1  ";
        //}else {
        //    sql = " SELECT id,username,password,email,gender,flag,role,code FROM tb_user "+where+" AND flag!=1 AND role=1 ";
        }
        try {
            return queryRunner.query(sql,new BeanListHandler<>(User.class),params.toArray());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteId(int did) {
        String sql=" DELETE FROM `tb_user` WHERE `id`=? ";
        try {
            queryRunner.update(sql,did);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User selectById(Integer uid) {
        String sql = " SELECT * FROM tb_user WHERE id=? ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(User.class),uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
